import React, {useEffect, useState, useRef, useCallback} from "react";
import {useHistory} from "react-router-dom";
import Lazyload, {forceCheck} from 'react-lazyload'
import Scroll from '@/components/scroll'

import './index.scss'
import {renderRoutes} from "react-router-config";
import loading from '@/assets/1.gif'
import {INew} from "@/common/model";
import {reqfind} from "@/common/api";

const Find: React.FC<any> = (props) => {

  console.log("-------Find------")

  const subRoutes = props.route.routes

  const history = useHistory()

  const scrollRef: any = useRef()

  const [findData, setFindData] = useState<any[]>([])

  // 上拉加载更多
  const handlePullUp = (fn: Function) => {
    getFindData(2)
    setTimeout(() => {
      fn()
    }, 800)
  }

  // 下拉刷新
  const handlePullDown = (fn: any) => {
    console.log('下拉刷新')
    getFindData(1)
    setTimeout(() => {
      fn()
    }, 800)
  }

  const getFindData = async (page: number) => {
    console.log('getFindData,page:', page)
    const {data}: any = await reqfind(page);
    if (page === 1) {
      setFindData(data);
    } else {
      console.log('33333333')
      setFindData([...findData, ...data]);
    }
  }

  const gotoNews = (item: any) => {
    history.push({pathname: `/find/${item.id}`, state: item})
  }

  useEffect(() => {
    getFindData(1);
  }, [])

  useEffect(() => {
    console.log('----', findData)
    if (scrollRef.current) {
      scrollRef.current.refreshScroll()
    }
  }, [findData])

  return (
    <div className="main">
      <div className="title">发现</div>

      <Scroll
        ref={scrollRef}
        direction="vertical" // 垂直滚动
        pullUp={handlePullUp}
        pullDown={handlePullDown}
        data={findData}
      >
        <div className="container">
          <div className="teslaFind">
            <img alt="" src={require('@/assets/find/a.png')}/>
          </div>
          <div className="teslaNews">
            {
              findData.map((item, index) => {
                return (
                  <div className="news" key={index} onClick={() => gotoNews(item)}>
                    <div className="newsLeft">
                      <h1>{item.title}</h1>
                      <p>{item.date}</p>
                    </div>
                    <div className="newsRight">
                      <Lazyload height={100} placeholder={<img alt="" width="100%" height="100%" src={loading}/>}>
                        <img alt="" src={require('@/assets/find/' + item.picUrl)}/>
                      </Lazyload>
                    </div>
                  </div>
                )
              })
            }
          </div>
        </div>
      </Scroll>
      {renderRoutes(subRoutes)}
    </div>
  )
}

export default Find
